import { useEffect } from "react";
import { useReactive } from "ahooks";
import { useModel } from "umi";
import { useOrganizationMember } from "@share-code/public";

function personInfoModel() {
    const { graphqlFetch } = useModel("global");
    const { loadOrganizationMemberInfo } = useOrganizationMember(graphqlFetch);

    let state = useReactive({
        accountInfo: {},
        baseInfo: {},
        loginInfo: {},
        memberInfo: {},
        settings: {},
        identity: "guest", // 当前用户身份：guest 游客(未登录); localLogined  本地登录; remoteLogined 公共认证中心登录; temporaryLogined 公共认证中心临时登录
    });

    useEffect(() => {
        const remotePersonInfo = remote.getGlobal("personInfo");
        for (let key in remotePersonInfo) {
            state[key] = remotePersonInfo[key];
        }
    }, []);

    const loadMemberInfo = async () => {
        let res = await loadOrganizationMemberInfo(state.baseInfo.uuid);
        state.memberInfo = res || {};
    };

    useEffect(() => {
        state.baseInfo?.uuid && loadMemberInfo();
    }, [state.baseInfo]);

    const setPersonStateValue = (obj) => {
        for (let key in obj) {
            state[key] = obj[key];
        }
    };

    return {
        ...state,
        setPersonStateValue,
    };
}

export default personInfoModel;
